package core

import (
	"encoding/json"
	"freechat-im/model"
	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
)

// 定义client，表示一个客户端
type Client struct {
	conn *websocket.Conn
	send chan *Data
}
type Data struct {
	Bytes []byte
	Meta  *map[string]string
}

// readPump 从Websocket通道中读取数据
func (c *Client) readPump(hub *ChContext, userId string, handler *MessageHandler) {
	defer func() {
		hub.unregister <- c
		c.conn.Close()
	}()
	for {
		_, messageBytes, err := c.conn.ReadMessage()
		if err != nil {
			logrus.Info("从connection中Read数据时出错. userId="+userId+"\t err=", err.Error())
			break
		}

		logrus.Debug("从connection中Read数据 data = ", string(messageBytes))

		var messageWrap = &model.MessageWrap{}
		if err := json.Unmarshal(messageBytes, &messageWrap); err != nil {
			c.send <- &Data{Bytes: []byte("message format error! " + err.Error())}
			logrus.Warn("message format error!  err=", err.Error())
			continue
		}

		if messageWrap.Message == nil && messageWrap.Event == nil {
			c.send <- &Data{Bytes: []byte("缺少 message或event 数据!")}
			logrus.Warn("缺少 message或event 数据!")
			continue
		}
		messageWrap.UserId = userId
		//处理消息
		handler.Handle(messageWrap)
	}
}

// writePump 往Websocket通道中写数据
func (c *Client) writePump(handler *MessageHandler) {
	defer func() {
		c.conn.Close()
	}()

	for message := range c.send {
		err := c.conn.WriteMessage(websocket.TextMessage, message.Bytes)
		if err != nil {
			logrus.Error("往connection中Write数据时出错. err=", err.Error())
			if message.Meta != nil {
				handler.AsyncCallback(*message.Meta, false)
			}
			break
		} else {
			if message.Meta != nil {
				handler.AsyncCallback(*message.Meta, true)
			}
			logrus.Debug("往connection中Write数据完成. ")
		}
	}
}
